package cqrtplm.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.excel.EasyExcel;
import com.hustcad.plm.pdm.common.model.vo.tableview.inittableview.PartAttrsVO;
import com.hustcad.plm.pdm.container.mapper.TyplmPdmLinkProductMapper;
import com.hustcad.plm.pdm.doc.dto.CreateDocInputDTO;
import com.hustcad.plm.pdm.doc.dto.SaveDocDTO;
import com.hustcad.plm.pdm.doc.service.TyplmDocumentService;
import com.hustcad.plm.pdm.file.model.dto.FileGroupDTO;
import com.hustcad.plm.pdm.folder.mapper.TyplmSubfolderMapper;
import com.hustcad.plm.pdm.iba.model.dto.SaveObjIBADTO;
import com.hustcad.plm.pdm.iba.service.TyplmAttributeValueService;
import com.hustcad.plm.pdm.lifestage.service.TyplmLifecycleTemplateService;
import com.hustcad.plm.pdm.middle.partbom.service.TyplmPdmPartService;
import com.hustcad.plm.pdm.partbom.vo.PdmPartInfoVO;
import com.hustcad.plm.pdm.type.service.TyplmTypeService;
import com.hustcad.plm.workspace.service.TyPlmWorkspaceObjectService;
import com.hustcad.plm.workspace.vo.ObjNumberErrorVO;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.dto.constraint.IbaDTO;
import com.ty.basic.entity.CTyEntityBaseDO;
import com.ty.basic.entity.folder.SubfolderDO;
import com.ty.basic.entity.lifecycle.LifeCycleTemplateDO;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.entity.part.PartDO;
import com.ty.basic.entity.product.PdmLinkProductDO;
import com.ty.basic.session.TyAccountContext;
import com.ty.basic.utils.BatchQueryHelper;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.dto.ImportStandardPartDTO;
import cqrtplm.service.RtCertApplicationService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RtCertApplicationServiceImpl implements RtCertApplicationService {

    private BigInteger lifeCycleTemplateOid;
    @Resource
    private TyplmLifecycleTemplateService typlmLifecycleTemplateService;
    @Resource
    private TyplmPdmLinkProductMapper typlmPdmLinkProductMapper;
    @Resource
    private TyplmSubfolderMapper typlmSubfolderMapper;
    @Resource
    private TyPlmWorkspaceObjectService tyPlmWorkSpaceObjectService;
    @Resource
    private TyplmAttributeValueService typlmAttributeValueService;
    @Resource
    private TyplmPdmPartService typlmPdmPartService;
    @Resource
    private TyplmTypeService typlmTypeService;
    @Resource
    private TyplmDocumentService typlmDocumentService;

    @Override
    public void CreateNewDocObject(String ctype,String backupType,String code) {
        try {

            LifeCycleTemplateDO lifeCycleTemplateDO = typlmLifecycleTemplateService.queryLifecycleByName(
                    "基本生命周期");
            lifeCycleTemplateOid = lifeCycleTemplateDO.getOid();
            //产品库-文档库
            PdmLinkProductDO pdmLinkProductDO = getPdmLinkProductDO("文档库");

            //文档库下文件夹 文件夹/认证模块
            String folderName = "认证模块";

            SubfolderDO subfolderDO = getSubfolderDO(pdmLinkProductDO, folderName);

            //如果有子文件夹 文件夹/认证模块/国2
            //SubfolderDO subfolderDO = getSubfolderDO(pdmLinkProductDO, "国2");

            if(subfolderDO==null){
                throw RTErrorCodeEnum.DOC_TYPE_ERROR.getException("文件夹:"+folderName+"不存在");
            }

            CreateDocInputDTO createDocInputDTO = new CreateDocInputDTO();
            String documentType = "国二";//类型的末级内部名称
            if (StringUtils.isBlank(documentType)) {
                throw RTErrorCodeEnum.DOC_TYPE_ERROR.getException("文档类型不能为空");
            }
            BigInteger typeOid = typlmTypeService.getTypeOidByName(documentType);//类型的末级内部码
            if (typeOid == null) {
                throw RTErrorCodeEnum.DOC_TYPE_ERROR.getException("类型["+documentType+"]在系统中不存在");
            }

            UserDO user = TyAccountContext.getUser();
            if (user == null) {
                //return ResponseResult.fail("401", "用户未登录");
                throw new RuntimeException("用户未登录");
            }

            createDocInputDTO.setNumber(code);
            createDocInputDTO.setName(StringUtils.trim(ctype));
            createDocInputDTO.setDocType(documentType);
            createDocInputDTO.setType(typeOid.toString());
            createDocInputDTO.setCreator(user.getName());
            createDocInputDTO.setFolderId(String.valueOf(subfolderDO.getOid()));
            createDocInputDTO.setContainerId(String.valueOf(pdmLinkProductDO.getOid()));
            createDocInputDTO.setContainerType(TableTypeConstrant.TY_PDMLINKPRODUCT_OTYPE);
            createDocInputDTO.setProductInfoID(String.valueOf(pdmLinkProductDO.getOid()));

//            String filePath = dto.getFilePath();
//            log.info("================>filePath:{}", filePath);
//            MultipartFile multipartFile = convertToMultipartFile(filePath);
//            List<MultipartFile> multipartFiles = new ArrayList<>();
//            multipartFiles.add(multipartFile);
//            FileGroupDTO fileGroupDto = new FileGroupDTO();
//            fileGroupDto.setFiles(multipartFiles);
            String docTypeOid = createDocInputDTO.getType();//文档类型的类型 末级
            if (StringUtils.isNotBlank(docTypeOid)) {
                this.typlmTypeService.checkTypeInstance(Collections.singletonList(new BigInteger(docTypeOid)));
            }
            Map<String, List<String>> ibaMap = new HashMap<>();
            //ibaMap.put("BACKUPTYPE", Collections.singletonList(backupType));
            ibaMap.put("customerModel", Collections.singletonList(backupType));

            SaveDocDTO saveDocDto = new SaveDocDTO();//文档对象保存的固定对象
            saveDocDto.setCreateDocInputDTO(createDocInputDTO);
            saveDocDto.setIbaAttribute(ibaMap);
            //saveDocDto.setFileGroupDto(fileGroupDto);
            typlmDocumentService.insertDoc(saveDocDto);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private PdmLinkProductDO getPdmLinkProductDO(String productName) {
        List<PdmLinkProductDO> pdmLinkProductDOS = BatchQueryHelper.queryExampleColumnIn(ListUtil.toList(productName),
                                                                                         PdmLinkProductDO.class,
                                                                                         "name",
                                                                                         typlmPdmLinkProductMapper);
        if(CollUtil.isEmpty(pdmLinkProductDOS)){
            throw RTErrorCodeEnum.DESCRIBE_RULE_ERROR.getException(
                    "创建文件对象失败，文件库在系统中不存在");
        }
        return pdmLinkProductDOS.get(0);
    }

    private SubfolderDO getSubfolderDO(PdmLinkProductDO pdmLinkProductDO,String key) {
        Example exampleSubfolder = new Example(SubfolderDO.class, true, true);
        Example.Criteria criteriaSubfolder = exampleSubfolder.createCriteria();
        criteriaSubfolder.andEqualTo("name",key).andEqualTo("containeroid",
                                                            pdmLinkProductDO.getOid()).andEqualTo("containerotype",
                                                                                                  pdmLinkProductDO.getOtype());
        List<SubfolderDO> subfolderDOS = typlmSubfolderMapper.selectByExample(exampleSubfolder);
        if(CollUtil.isEmpty(subfolderDOS)){
            throw RTErrorCodeEnum.DESCRIBE_RULE_ERROR.getException(
                    "创建认证对象失败，认证模块文件夹在系统中不存在");

        }
        return subfolderDOS.get(0);
    }

    /**
     * 查询指定编码的物料在系统中是否已经存在
     */
    private boolean checkPartExistByNumber(String ctype,String backupType) {
//        List<String> objNumberList = new ArrayList<>();
//        objNumberList.add(partNumber);
//        List<ObjNumberErrorVO> objNumberErrorVOS = tyPlmWorkSpaceObjectService.judgeObjNumberIsExist(objNumberList,
//                                                                                                     "ty.inteplm.part.CTyPart");
//        if (objNumberErrorVOS != null && !objNumberErrorVOS.isEmpty()) {
//            ObjNumberErrorVO objNumberErrorVO = objNumberErrorVOS.get(0);
//            return objNumberErrorVO.isExist();
//        }
        return true;
    }

    private static void addIbaDto(String value, List<IbaDTO> ibaDTOList,String key) {
        IbaDTO ibaDTO = new IbaDTO();
        ibaDTO.setKey(key);
        ibaDTO.setValue(value);
        ibaDTOList.add(ibaDTO);
    }
}
